package org.example.classtopia.Controller;

import org.example.classtopia.Model.dto.CategoryCreateDTO;
import org.example.classtopia.Model.dto.CategoryUpdateDTO;
import org.example.classtopia.Model.vo.CategoryVO;
import org.example.classtopia.Service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类控制器
 */
@RestController
@RequestMapping("/categories")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public CategoryVO createCategory(@RequestBody CategoryCreateDTO dto) {
        if (!StringUtils.hasText(dto.getName())) {
            throw new IllegalArgumentException("分类名称不能为空");
        }
        CategoryVO vo = new CategoryVO();
        var entity = categoryService.createCategory(dto);
        if (entity == null) {
            throw new RuntimeException("分类创建失败");
        }
        return categoryService.getCategoryById(entity.getId());
    }

    @GetMapping("/{id}")
    public CategoryVO getCategoryById(@PathVariable Long id) {
        CategoryVO vo = categoryService.getCategoryById(id);
        if (vo == null) {
            throw new RuntimeException("分类不存在");
        }
        return vo;
    }

    @GetMapping
    public List<CategoryVO> getAllCategories(@RequestParam(defaultValue = "0") int page,
                                             @RequestParam(defaultValue = "10") int size) {
        int offset = page * size;
        return categoryService.getAllCategories(offset, size);
    }

    @PutMapping
    public boolean updateCategory(@RequestBody CategoryUpdateDTO dto) {
        if (dto.getId() == null) {
            throw new IllegalArgumentException("分类ID不能为空");
        }
        return categoryService.updateCategory(dto);
    }

    @DeleteMapping("/{id}")
    public boolean deleteCategory(@PathVariable Long id) {
        return categoryService.deleteCategoryById(id);
    }
}

